// use std::{fs::File, path::PathBuf};

use std::{
    any::Any,
    collections::HashMap,
    io::{Cursor, Read, Write},
};

use serde::Serialize;
use tube::Value;
// use html2pdf;
use docx_rs::*;
use serde_json::json;
fn main() {
    let file = std::fs::File::create("table.docx").unwrap();
    let mut docx = Docx::new().add_paragraph(
        Paragraph::new()
            .add_run(
                Run::new()
                    .add_text("成都瑞宬汽车服务有限公司居间服务协议")
                    .underline("single"),
            )
            .style("Heading1"),
    );
    let data = json!([
        {
            "type":"table",
            "border":"no",
            "key":"commpany_info",
            "grid":[2000, 2000, 2000, 2000],
            "data":[
                [{"text":"甲  方: "},{"text":"成都瑞宬汽车服务有限公司"},{"text":"乙  方: "},{"text":"南充欧锐"}],
                [{"text":"地  址: "},{"text":"龙泉驿区成龙大道2段博美装饰城5号馆"},{"text":"地  址: "},{"text":"南充"}],
                [{"text":"联系人: "},{"text":"袁洲权"},{"text":"联系人: "},{"text":"刘"}],
                [{"text":"电  话："},{"text":"龙泉驿区成龙大道2段博美装饰城5号馆"},{"text":"电  话: "},{"text":"18784704560"}]
            ]
        }
    ]);
    let list = Value::from(data).as_array().unwrap();
    for item in list.iter() {
        println!("---{}", item["type"].to_string());
        let ty = item["type"].to_string();
        let border = item["border"].to_string();
        if ty.eq("table") {
            let mut rows = vec![];
            let d_rows = item["data"].as_array().unwrap();
            for r in d_rows.iter() {
                println!("--{:?}", r);
                let mut cells = vec![];
                let d_cols = r.as_array().unwrap();
                for c in d_cols.iter() {
                    cells.push(
                        TableCell::new()
                            .add_paragraph(Paragraph::new().add_run(
                                Run::new().add_text(&format!("{}", c["text"].to_string())),
                            ))
                            .vertical_align(VAlignType::Center)
                            .vertical_merge(VMergeType::Restart),
                    );
                }
                rows.push(TableRow::new(cells));
            }
            let grid = item["grid"]
                .as_array()
                .unwrap()
                .iter()
                .map(|x| x.to_u32() as usize)
                .collect::<Vec<usize>>();
            let mut tbl = Table::new(rows).set_grid(grid);
            if border == "no" {
                tbl = tbl.clear_all_border();
            }
            docx = docx.add_table(tbl);
        }
    }
    docx.build().pack(file);

    
    // 读取docx
    let mut file = std::fs::File::open("contract2.docx").unwrap();
    let mut buf = vec![];
    file.read_to_end(&mut buf).unwrap();
    // 解压docx中xml
    read_docx_c(&buf);


    // 转换成docx_rs中对象，并转换成json,保存到文件中
    let res = read_docx(&buf).unwrap().json();
    let mut file = std::fs::File::create("hello.json").unwrap();
    file.write_all(res.as_bytes()).unwrap();
    file.flush().unwrap();

    // let s=from_utf8(&buf).unwrap();

    let mut dic = HashMap::new();
    dic.insert(
        "{{firstPartName}}".to_owned(),
        "成都瑞宬汽车服务有限公司".to_owned(),
    );
    dic.insert(
        "{{firstPartAddress}}".to_owned(),
        "龙泉驿区成龙大道2段博美装饰城5号馆".to_owned(),
    );
    dic.insert("{{firstPartContact}}".to_owned(), "袁洲权".to_owned());
    dic.insert("{{firstPartMobile}}".to_owned(), "15928046967".to_owned());
    dic.insert("{{secondPartName}}".to_owned(), "南充欧锐".to_owned());
    dic.insert("{{secondPartAddress}}".to_owned(), "南充".to_owned());
    dic.insert("{{secondPartContact}}".to_owned(), "刘".to_owned());
    dic.insert("{{secondPartMobile}}".to_owned(), "18784704560".to_owned());

    let mut doc2 = read_docx(&buf).unwrap();

    for f in &mut doc2.document.children {
        match *f {
            DocumentChild::Paragraph(ref p) => {
                let key = p.raw_text();
                if dic.contains_key(&key) {
                    // p.property[""]="";
                }
                // println!("{:?}",p.raw_text());
            }
            DocumentChild::Table(_) => {}
            DocumentChild::BookmarkStart(_) => {}
            DocumentChild::BookmarkEnd(_) => {}
            DocumentChild::CommentStart(_) => {}
            DocumentChild::CommentEnd(_) => {}
            DocumentChild::StructuredDataTag(_) => {}
            DocumentChild::TableOfContents(_) => {}
        }
    }
}

const DOC_RELATIONSHIP_TYPE: &str =
    "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument";
const CUSTOM_PROPERTIES_TYPE: &str =
    "http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties";

///解压docx中的xml
pub fn read_docx_c(buf: &[u8]) -> core::result::Result<(), ReaderError> {
    let mut docx = Docx::new();
    let cur = Cursor::new(buf);
    let mut archive = zip::ZipArchive::new(cur)?;

    // Next, the single required relationship (the package-level relationship to the Main Document part)
    //  must be defined (physically located at /_rels/.rels in the package)
    let rels = {
        let data = read_zip(&mut archive, "_rels/.rels")?;
        Rels::from_xml(&data[..])?
    };

    // Finally, the minimum content for the Main Document part must be defined
    // (physically located at /document.xml in the package):
    let main_rel = rels
        .find_target(DOC_RELATIONSHIP_TYPE)
        .ok_or(ReaderError::DocumentNotFoundError);

    let document_path = if let Ok(rel) = main_rel {
        rel.2.clone()
    } else {
        "word/document.xml".to_owned()
    };

    if let Some(custom_props) = rels.find_target(CUSTOM_PROPERTIES_TYPE) {
        let data = read_zip(&mut archive, &custom_props.2);

        if let Ok(data) = data {
            if let Ok(custom) = CustomProps::from_xml(&data[..]) {
                docx.doc_props.custom = custom;
            }
        }
    }
    let mut dic = HashMap::new();
    dic.insert(
        "{{firstPartName}}".to_owned(),
        "成都瑞宬汽车服务有限公司".to_owned(),
    );
    dic.insert(
        "{{firstPartAddress}}".to_owned(),
        "龙泉驿区成龙大道2段博美装饰城5号馆".to_owned(),
    );
    dic.insert("{{firstPartContact}}".to_owned(), "袁洲权".to_owned());
    dic.insert("{{firstPartMobile}}".to_owned(), "15928046967".to_owned());
    dic.insert("{{secondPartName}}".to_owned(), "南充欧锐".to_owned());
    dic.insert("{{secondPartAddress}}".to_owned(), "南充".to_owned());
    dic.insert("{{secondPartContact}}".to_owned(), "刘".to_owned());
    dic.insert("{{secondPartMobile}}".to_owned(), "18784704560".to_owned());
    dic.insert("{{productName}}".to_owned(), "一汽大从".to_owned());
    dic.insert("{{spec}}".to_owned(), "123T99.激发".to_owned());
    dic.insert("{{color}}".to_owned(), "黑色".to_owned());
    let document = {
        let data = read_zip(&mut archive, &document_path)?;
        let mut template_str=std::str::from_utf8(&data).unwrap().to_owned();

        for (key,v) in dic{
            template_str=template_str.replace(&key,&v);
        }
       
        Document::from_xml(template_str.as_bytes())?
    };
    docx = docx.document(document);
    let file = std::fs::File::create("table.docx").unwrap();
    docx.build().pack(file);
    Ok(())
}
